﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using VietTrips.Domain.Interfaces;
using VietTrips.Domain.Models;
using VietTrips.Domain.Repositories;

namespace VietTrips.Domain.Services
{
    public partial class TourAgenciesService
    {
        private readonly ITourAgencyRepository _tourAgencyRepository;
        private readonly IUserRepository _userRepository;

        public TourAgenciesService()
        {
            _userRepository = new UserRepository();
            _tourAgencyRepository = new TourAgencyRepository();
        }

        public TourAgency GetAgencyByUser(string username)
        {
            var manager = _userRepository.FindByUsername(username);
            return _tourAgencyRepository.All.FirstOrDefault(t => t.ManagerId == manager.UserId);
        }

        public void RegisterNewAgency(TourAgency agency)
        {
            try
            {
                _tourAgencyRepository.Insert(agency);

                var manager = _userRepository.Find((agency.ManagerId ?? 0));
                bool check = false;
                check = Roles.IsUserInRole(manager.UserName, "Administrator");
                check = check != false || Roles.IsUserInRole(manager.UserName, "Agency");

                if (!check)
                {
                    Roles.AddUserToRole(manager.UserName, "Agency");
                }

                _tourAgencyRepository.Save();
            }
            catch (Exception)
            {
                
                throw;
            }
            
        }
    }
}
